//
//  SelectedSeasonController.m
//  ArandaTest
//
//  Created by Camilo Cadena on 2/18/15.
//  Copyright (c) 2015 Camilo Cadena. All rights reserved.
//

#import "SelectedSeasonController.h"
#import "test1HeaderConstants.h"
#import "ServicesStrings.h"
#import "AFNetworking.h"
#import "EpisodeObject.h"

@implementation SelectedSeasonController

// Request the selected season episodes
-(void)requestEpisodesForSeries:(NSString *)series season:(NSString *)season andCompletionBlock:(void(^)(id))completionBlock{
    
    //build request
    NSString *request = [ServicesStrings getUrlFromString:KSERVICE andString:[NSString stringWithFormat:KEPISODES_BY_SEASON,series,season]];
    NSDictionary *params = @{@"api_key":KAPI_KEY};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //Calcel pending and/or on going operations if requested
    [[manager operationQueue] cancelAllOperations];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager GET:request parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *responseDictionary = [[NSDictionary alloc] initWithDictionary:responseObject];
        NSArray *results = [[NSArray alloc] initWithArray:[responseDictionary valueForKey:@"episodes"]];
        NSMutableArray *finalResults = [[NSMutableArray alloc] init];
        for(int i=0; i<results.count; i++){
            EpisodeObject *item = [EpisodeObject instanceFromDictionary:[results objectAtIndex:i]];
            [finalResults addObject:item];
        }
        completionBlock(finalResults);
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        completionBlock(error);
    }];
    
}


@end
